# frozen_string_literal: true

require_relative '../../../../../spec_helper'
require 'wpxf/modules'

describe Wpxf::Auxiliary::SiteEditorFileDownload do
  let(:subject) { described_class.new }
  let(:downloaded_filename) { File.join(Dir.tmpdir, 'wpxf_unit_test') }

  before :each, 'setup subject' do
    allow(subject).to receive(:check_plugin_version_from_readme)
    allow(subject).to receive(:downloaded_filename).and_return(downloaded_filename)
  end

  after :each, 'delete temp files' do
    FileUtils.rm_f downloaded_filename
  end

  it 'should return a {Wpxf::Module}' do
    expect(subject).to be_a Wpxf::Module
  end

  it 'should check the plugin version is < 1.1.2' do
    subject.check
    expect(subject).to have_received(:check_plugin_version_from_readme)
      .with('site-editor', '1.1.2')
      .exactly(1).times
  end

  it 'should register the default remote file path' do
    expected = '/etc/passwd'
    expect(subject.default_remote_file_path).to eql expected
  end

  it 'should not require authentication' do
    expect(subject.requires_authentication).to be false
  end

  it 'should configure the working directory' do
    expected = 'wp-content/plugins/site-editor/editor/extensions/pagebuilder/includes/'
    expect(subject.working_directory).to eql expected
  end

  it 'should configure the downloader url' do
    expected = %r{site\-editor/editor/extensions/pagebuilder/includes/ajax_shortcode_pattern\.php}
    expect(subject.downloader_url).to match(expected)
  end

  it 'should configure the request params' do
    subject.set_option_value('remote_file', '/etc/passwd')
    expect(subject.download_request_params).to eql('ajax_path' => '/etc/passwd')
  end

  it 'should GET the download request' do
    expect(subject.download_request_method).to eql :get
  end

  it 'should remove junk data from the end of the file during validation' do
    content = 'root:toor{"success":true,"data":{"output":[]}}'
    subject.validate_content(content)
    modified_content = File.read(downloaded_filename)
    expect(modified_content).to eql 'root:toor'
  end
end
